package edu.stanford.prpl.impl.directory;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import edu.stanford.prpl.api.Device;
import edu.stanford.prpl.common.PRPLProperties;
import edu.stanford.prpl.common.util.URIUtils;
import edu.stanford.prpl.impl.DeviceImpl;

public class DirectoryCommon {

	public static final String GLOBAL_DIR_API_NAME = "prpl-directory";
	public static final String PCM_DIR_API_NAME = "prpl";

	public static final String IDENTITY_URI = "IDENTITY_URI";
	public static final String IDENTITY_KEY = "IDENTITY_KEY";
	public static final String IDENTITY_NAME = "IDENTITY_NAME";
	public static final String IDENTITY_SERVER_URL = "IDENTITY_SERVER_URLs";
	public static final String DEVICE_NAME = "DEVICE_NAME";
	public static final String DEVICE_SERVER_URL = "DEVICE_SERVER_URL";
	public static final String DEVICE_ROLES = "DEVICE_ROLES";
	public static final String DEVICE_URI = "DEVICE_URI";

	public static Device getDeviceFromPersonalDirectoryEntry(Map<String, String> map) throws MalformedURLException {
		if (map == null)
			return null;
		// String deviceName = map.get(DEVICE_NAME);
		String deviceURI = map.get(DEVICE_URI);
		URL deviceServerURL = new URL(map.get(DEVICE_SERVER_URL));
		String deviceRoles = map.get(DEVICE_ROLES);
		Device device = new DeviceImpl(deviceURI, deviceServerURL, deviceRoles.split(" "));
		return device;
	}

	public static Map<String, String> getGlobalDirectoryEntry(Device device) throws UnknownHostException {

		if (!device.isPCM())
			return null;

		Map<String, String> entry = new HashMap<String, String>();

		String userKey = PRPLProperties.getProperty("prpl.user.key");
		String userName = PRPLProperties.getProperty("prpl.user.name");
		entry.put(IDENTITY_URI, URIUtils.getIdentityURI(userKey));
		entry.put(IDENTITY_KEY, userKey);
		entry.put(IDENTITY_NAME, userName);
		entry.put(IDENTITY_SERVER_URL, device.getServerURL().toString());
		return entry;
	}

	public static Map<String, String> getPersonalDirectoryEntry(Device device) throws URISyntaxException {
		Map<String, String> entry = new HashMap<String, String>();
		entry.put(DEVICE_URI, device.getURI());
		entry.put(DEVICE_NAME, device.getName());
		entry.put(DEVICE_SERVER_URL, device.getServerURL().toURI().toASCIIString());

		StringBuffer sb = new StringBuffer();
		sb.append((device.isPCM()) ? DeviceImpl.PCM_DEVICE + " " : "");
		sb.append((device.isBlobServer()) ? DeviceImpl.BLOB_SERVER_DEVICE + " " : "");
		sb.append((device.isCache()) ? DeviceImpl.CACHE_DEVICE + " " : "");
		entry.put(DEVICE_ROLES, sb.toString());

		return entry;
	}

}
